package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart) {
        //判断添加的菜品或者套餐
        Long dishId = shoppingCart.getDishId();
        //获取登录用户id
        Long UserId = BaseContext.getContext();
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, UserId);
        if (dishId != null) {
            //当前添加是菜品
            lqw.eq(ShoppingCart::getDishId, dishId);
        } else {
            //当前添加是套餐
            lqw.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        }
        //查询
        ShoppingCart cart = shoppingCartService.getOne(lqw);
        //判断购物车中是否已经有该菜品或套餐
        if (cart != null) {
            //购物车里已经有了该菜品或套餐
            cart.setNumber(cart.getNumber() + 1);
            shoppingCartService.updateById(cart);
        }else {
            //购物车中没有该菜品
            shoppingCart.setNumber(1);
//            cart.setUserId(UserId);
            shoppingCart.setUserId(UserId);
            shoppingCartService.save(shoppingCart);
            cart = shoppingCart;
        }
        return R.success(cart);
    }

    /**
     * 查询购物车
     * @return
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list(){
        //条件构建器
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,BaseContext.getContext());
        lqw.orderByDesc(ShoppingCart::getCreateTime);

        //2.查询
        List<ShoppingCart> list = shoppingCartService.list(lqw);
        return R.success(list);
    }

    /**
     * 删除购物车
     * @return
     */
    @DeleteMapping("/clean")
    public R<String> clean(){
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,BaseContext.getContext());

        //删除
        shoppingCartService.remove(lqw);
        return R.success("删除成功");
    }


}
